package com.lagou.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    //获得applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //获取Bean
    public static <T> T getBean(Class<T> requiredType){
        return (T) getApplicationContext().getBean(requiredType);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        return (T) getApplicationContext().getBean(name);
    }
}
